//microcommand define 赞我
const { Temporal } = require("temporal-polyfill")
ctx = ctx.platform("onebot")
signature("[times:posint]", { checkArgCount: true, checkUnknown: true })
alias("sendlike")
action(async ({ root, session }, times) => {
  res = await main(session, times)
  if (root && !session.isDirect) res.unshift(h.quote(session.messageId))
  return res
})
async function main(session, times) {
  const maxLikesSendable = (await session.onebot.getStrangerInfo(session.selfId)).is_vip ? 20 : 10
  const { favoriteInfo, voteInfo } = await session.onebot._get("get_profile_like", { user_id: session.userId })
  const userVoteInfo = voteInfo.userInfos[0]

  let message

  const today = Temporal.Now.plainDateISO("+08")
  const lastSentLikeTime = Temporal.Instant.fromEpochMilliseconds((userVoteInfo?.latestTime ?? 0) * 1000).toZonedDateTimeISO("+08")
  const likesSentToday = today.equals(lastSentLikeTime) ? userVoteInfo.count : 0
  const alreadyMaxed = likesSentToday >= maxLikesSendable
  if (alreadyMaxed) message = session.i18n(".maxed")
  const isMaxing = !times || times >= maxLikesSendable - likesSentToday
  if (isMaxing) times = maxLikesSendable - likesSentToday

  if (!message) {
    const r = await session.onebot._request("send_like", {
      user_id: session.userId,
      times,
    })
    if (r.retcode) {
      if (r.message?.match?.(/已达.*?上限/)) {
        message = session.i18n(".maxed")
      } else if (r.message?.includes?.("权限设置")) {
        return session.i18n(".no-permission")
      } else {
        ctx.logger.error(r.retcode, r.message)
        return session.i18n("internal.error-encountered")
      }
    }
  }
  if (!message) message = [h("face", { platform: "onebot", id: "76" }), ...session.i18n(".done", [times])]

  if (isMaxing && favoriteInfo?.last_time && Math.random() < 0.666) try {
    let flavor

    const lastReceivedLikeDate = Temporal.PlainDate.from({
      year: ~~(favoriteInfo.last_time / 10000),
      month: ~~(favoriteInfo.last_time / 100) % 100,
      day: favoriteInfo.last_time % 100,
    })
    const daysSinceLastReceivedLike = today.since(lastReceivedLikeDate).total("days")
    const flavorKeys = []
    if (daysSinceLastReceivedLike === 0) {
      flavorKeys.push(".flavor.thanks.general")
    } else {
      if (daysSinceLastReceivedLike === 1 && Math.random() < 0.5)
        flavorKeys.push(".flavor.ask.liked-yesterday")
      flavorKeys.push(".flavor.ask.general")
    }
    message.push(...session.i18n([...flavorKeys, ""]))
  } catch (err) {
    ctx.logger.warn("check received like info", err)
  }

  return message
}
locale("zh-CN", {
  description: "给你的QQ资料卡点赞",
  messages: {
    done: "赞了你 {0} 次。",
    flavor: {
      ask: {
        general: "记得回赞哦～",
        "liked-yesterday": "今天也会继续给 LNNBot 点赞吗？",
      },
      thanks: {
        general: "也谢谢你今天给 LNNBot 点赞啦～",
      }
    },
    "no-permission": "咦…好像赞不了，是不是没有打开“允许陌生人赞我”呢？",
    maxed: "咦…今天好像已经赞满了呢。",
  },
})